<?php
/**
 * Copyright (C), 2016-2018, Shall Buy Life info. Co., Ltd.
 * FileName:EcService.php
 * Description: 说明
 *
 * @author lwl
 * @Create Date 2021/12/20 10:26:09
 * @Update Date 2021/12/20 10:26:09
 * @version v1.0
 */
declare(strict_types=1);

namespace Example\Services;

use Example\Constants\RefundConstant;
use Example\Constants\TccConstant;
use Example\Models\Refund;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

final class TccService implements TccConstant
{

    public function storeRefund(string $orderSn, $refundMoney): array
    {
        // TODO: Implement storeRefund() method.
        DB::beginTransaction();
        try {
            $data = \YiMQ::transaction('decoration.order.refund.create.tcc', function () use ($orderSn, $refundMoney) {
                $refundResponse = \YiMQ::tcc('order@order.refund.create.tcc')->data(
                    [
                        'ordersn' => $orderSn,
                        'return_credits' => 0,
                        'refund_money' => $refundMoney,
                        'refund_credits' => 0,
                        'refund_coin' => 0,
                        'is_validate' => 1
                    ]
                )->try();
                $result = json_decode(json_encode($refundResponse), true);
                $order = Order::query()->where('order_sm',$orderSn)->first();
                $result['prepareData']['member_id'] = $order['member_id'];
                $result['prepareData']['order_sn'] = $orderSn;
                $result['prepareData']['status'] = RefundConstant::STATUS_APPLY_ING;
                $result['prepareData']['refund_money'] = $refundMoney;
                if (!Refund::query()->create($result['prepareData'])) {
                    DB::rollBack();
                    Log::channel('refund')->info('创建退款订单-错误', ['订单号' => $orderSn]);
                }
            })->delay(1000 * 20)->begin();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::channel('refund')->debug('创建-退款订单-异常', ['订单号' => $orderSn]);
            return ['code' => 500, 'data' => [], 'message' => $exception->getMessage()];
        }
        DB::commit();
        return ['code' => 200, 'data' => $data, 'message' => 'successful'];
    }
}
